﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OpenXLive;
using OpenXLive.Features;
using OpenXLive.Silverlight;
using System.IO;
using System.Windows.Media.Imaging;

namespace OpenXLiveSilverlight
{
    public partial class UpdateStatusPage : PhoneApplicationPage
    {
        /// <summary>
        /// Gets or sets the picture used to share.
        /// </summary>
        internal static byte[] SharingPicture { get; set; }
        /// <summary>
        /// The selected provider
        /// </summary>
        private SNSProvider _Provider;

        public UpdateStatusPage()
        {
            InitializeComponent();

            // Binding the SNS providers to ListBox control
            listBoxSNS.ItemsSource = XLiveGameManager.CurrentSession.SNSProviders;

            txtContent.TextChanged += new TextChangedEventHandler(txtContent_TextChanged);

            // Show the screen-shot on current UI page.
            ShowPicture();
        }

        // Share the content and picture
        private void Share(SNSContract contract)
        {
            if (string.IsNullOrEmpty(txtContent.Text))
                return;

            SharingPanel.Visibility = System.Windows.Visibility.Visible;
            ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
            ChoosePanel.Visibility = System.Windows.Visibility.Collapsed;

            // Get Published word
            GameProfile profile = XLiveGameManager.CurrentSession.Profile;

            string content = string.Format("我正在玩Windows Phone上的《疯狂猜歌词》，{0}。",
                                        txtContent.Text);

            // Create Status object and update status to social network
            MyStatus status = new MyStatus(contract);
            status.UpdateStatusCompleted += new OpenXLive.Features.AsyncEventHandler(status_SNSUpdateStatusCompleted);
            status.UpdateStatus(content, SharingPicture);

            System.Diagnostics.Debug.WriteLine("Update Status ......");
        }

        #region Asynchronous call return method
        
        // Handle update result
        void status_SNSUpdateStatusCompleted(object sender, AsyncEventArgs e)
        {
            MyStatus status = sender as MyStatus;

            if (status != null)
            {
                status.UpdateStatusCompleted -= new OpenXLive.Features.AsyncEventHandler(status_SNSUpdateStatusCompleted);
            }

            if (e.Result.ReturnValue)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    if (MessageBox.Show("发布成功") == MessageBoxResult.OK)
                    {
                        ContentPanel.Visibility = System.Windows.Visibility.Visible;
                    }
                });
            }
            else
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    MessageBoxResult result = MessageBox.Show(string.Format("发布失败! 需要重试吗? Error: {0}, Code: {1}", e.Result.ErrorMessage, e.Result.ErrorCode), "分享", MessageBoxButton.OKCancel);
                    if (result == MessageBoxResult.OK)
                    {
                        ContentPanel.Visibility = System.Windows.Visibility.Visible;
                    }
                    else if (result == MessageBoxResult.Cancel)
                    {
                        if (this.NavigationService.CanGoBack)
                            this.NavigationService.GoBack();
                    }
                });
            }
            this.Dispatcher.BeginInvoke(() =>
            {
                SharingPanel.Visibility = System.Windows.Visibility.Collapsed;
            });
        }

        /// Share content and picture if this page is navigated from SocialConnectPage and connect succeed
        private void ConnectCompleted(object sender, SocialConnectCompletedEventArgs e)
        {
            SNSContract contract = e.Contract;
            if (contract != null)
            {
                Share(contract);
            }
        }

        #endregion

        #region UI feature

        // Handle the picture used to share
        private void ShowPicture()
        {
            if (imageCap.Source == null)
            {
                byte[] picture = SharingPicture;

                if (picture.Length == 0)
                    throw new InvalidOperationException("There is no picture used to share.");

                MemoryStream ms = new MemoryStream();
                ms.Write(picture, 0, picture.Length);
                BitmapImage bi = new BitmapImage();
                bi.SetSource(ms);

                imageCap.Source = bi;
            }

            if (XLiveGameManager.CurrentSession != null &&
                XLiveGameManager.CurrentSession.SNSProviders.Count > 0)
            {
                _Provider = XLiveGameManager.CurrentSession.SNSProviders[0];
                UpdateSelectedProvider();
            }
        }

        void txtContent_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtError.Visibility == System.Windows.Visibility.Visible)
            {
                if (!string.IsNullOrEmpty(txtContent.Text))
                    txtError.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            // The content must not be null or empty
            if (string.IsNullOrEmpty(txtContent.Text))
            {
                txtError.Visibility = System.Windows.Visibility.Visible;
                return;
            }

            if (_Provider == null)
            {
                return;
            }

            if (XLiveGameManager.CurrentSession == null || !XLiveGameManager.CurrentSession.IsValid)
            {
                return;
            }

            MyPlayer player = XLiveGameManager.CurrentSession.CurrentPlayer;
            if (player == null)
            {
                return;
            }

            SNSContract contract = player.GetSNSContract(_Provider);

            // If the player has been connect the SNS account, share it use SNS Contract.
            if (contract != null)
            {
                Share(contract);
            }
            else
            {
                // If the player has been not connect the SNS account, show the UI of Scial Connect to get SNS contract.
                XLiveUIManager.ShowSocialConnect(_Provider, ConnectCompleted);
            }   
        }

        #endregion

        #region Choose SNS
        private void btnChoose_Tap(object sender, GestureEventArgs e)
        {
            TitlePanel.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
            ChoosePanel.Visibility = System.Windows.Visibility.Visible;
            SharingPanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void StackPanel_Tap(object sender, GestureEventArgs e)
        {
            FrameworkElement element = sender as FrameworkElement;
            SNSProvider provider = element.DataContext as SNSProvider;
            if (provider != null)
            {
                _Provider = provider;
                UpdateSelectedProvider();
                RestoreView();
            }
        }

        private void UpdateSelectedProvider()
        {
            if (_Provider != null)
            {
                Uri uri = null;
                Uri.TryCreate(_Provider.Logo, UriKind.Absolute, out uri);
                if (uri != null)
                {
                    SNSImage.Source = new BitmapImage(uri);
                }
                SNSName.Text = _Provider.Name;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (ChoosePanel.Visibility == System.Windows.Visibility.Visible)
            {
                RestoreView();
                e.Cancel = true;
            }
        }

        private void RestoreView()
        {
            ChoosePanel.Visibility = System.Windows.Visibility.Collapsed;
            SharingPanel.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Visible;
            TitlePanel.Visibility = System.Windows.Visibility.Visible;
        }
        #endregion
    }
}